//文件系统模块
const fs=require("fs");

//整体读取文件
fs.readFile("04pl.txt","utf-8",(err,data)=>{
    if(err){
        console.error(err);
    }else{
        console.log(data);
    }
});

//fs回调形式，并使用Buffer
fs.open("04pl.txt","r",function(err,fd){
    if(err) throw err;
    console.log("打开文件...")
    let buffer=Buffer.alloc(1024);
    fs.read(fd,buffer,0,buffer.length,0,function(err,bytesRead,buffer){
        if(err) throw err;
        console.log(`读取字节${bytesRead}`);
        console.log(buffer.subarray(0,bytesRead).toString())
        fs.close(fd,err=>{
            if(error) throw err;
        });
    });
});

const fsPromises=fs.promises;
(async function(file){
    let filehandle;
    try{
        filehandle=await fsPromises.open(file);
        console.log(`已经打开${file}文件`)
        let buffer=Buffer.alloc(1024);
        let res=await filehandle.read(buffer,0,buffer.length,0);
        console.log(`读取字节${res.bytesRead}\n`);
        console.log(`${res.buffer.toString()}`);
    }
    catch(error){
        console.log(error)
    }finally{
        if(filehandle){
            await filehandle.close();
        }
    }
})("04pl.txt");

//写文件
let data="Hello ,node.js,欢迎使用Node.js!";
fs.writeFile("04output.txt",data,"utf-8",function(err){
    if(err){
        console.error(err);
    
    }else
        console.log("写入完成");
})
